package com.jiot.plugin.shiro.tag;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import com.jiot.plugin.shiro.ShiroDbRealm;

/**
 * Created by lishuwen on 2017/6/23.
 */
public class ShiroTag {

    /**
     * The guest tag
     *
     * @return
     */
    public boolean isGuest() {
        return getSubject() == null || getSubject().getPrincipal() == null;
    }

    /**
     * The user tag
     *
     * @return
     */
    public boolean isUser() {
        return getSubject() != null && getSubject().getPrincipal() != null;
    }

    /**
     * The authenticated tag
     *
     * @return
     */
    public boolean isAuthenticated() {
        return getSubject() != null && getSubject().isAuthenticated();
    }

    public boolean isNotAuthenticated() {
        return !isAuthenticated();
    }

    /**
     * The hasRole tag
     *
     * @param roleName
     * @return
     */
    public boolean hasRole(String roleName) {
        return getSubject() != null && getSubject().hasRole(roleName);
    }

    /**
     * The lacksRole tag
     *
     * @param roleName
     * @return
     */
    public boolean lacksRole(String roleName) {
        boolean hasRole = getSubject() != null && getSubject().hasRole(roleName);
        return !hasRole;
    }

    /**
     * The hasPermission tag
     *
     * @param p
     * @return
     */
    public boolean hasPermission(String p) {
        return getSubject() != null && getSubject().isPermitted(p);
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取用户信息
     *
     * @return
     */
//    public static User getUser() {
//        String account = (String) getSubject().getPrincipals().getPrimaryPrincipal();
//        UserService userService = Duang.duang(UserService.class);
//        User user = userService.getUserByAccount(account);
//        return user;
//    }

    public static ShiroDbRealm getDbRealm() {
        RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        ShiroDbRealm dbRealm = (ShiroDbRealm) securityManager.getRealms().iterator().next();
        return dbRealm;
    }

}